package com.donger.common.sso.config;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.sso.SaSsoConsts;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpStatus;
import com.donger.common.core.utils.Res;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Map;

/**
 * @author pmc
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private PermitAllUrlProperties permitAllUrlProperties;

    @Bean
    public SaServletFilter getSaServletFilter() {

        SaServletFilter saServletFilter = new SaServletFilter()
                .addInclude("/**");

        permitAllUrlProperties.getIgnoreUrls().forEach(saServletFilter::addExclude);

        saServletFilter.setAuth(obj -> {
            if (!StpUtil.isLogin()) {
                try {
                    String serverUrl = SaManager.getConfig().getSso().getAuthUrl();
                    String serviceUrl = SaFoxUtil.joinParam(serverUrl, SaSsoConsts.ParamName.redirect + "=");
                    Map<Object, Object> url = MapUtil.builder().put("url", serviceUrl).build();
                    String err = objectMapper.writeValueAsString(Res.error("登录失败").data(url));
                    SaHolder.getResponse().setStatus(HttpStatus.HTTP_UNAUTHORIZED);
                    SaRouter.back(err);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
        });
        return saServletFilter;
    }
}
